package org.elfen.common.base;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.elfen.common.Constants;
import org.elfen.common.json.JsonUtil;
import org.elfen.common.result.Result;
import org.elfen.common.scan.StringEscapeEditor;
import org.elfen.common.util.DataUtil;
import org.elfen.common.util.DateUtil;
import org.elfen.common.util.WebUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;

/**
 * 控制器基类
 * 
 */
public abstract class BaseController {
	private static final Logger logger = LoggerFactory.getLogger(BaseController.class);
	protected HttpServletRequest request;
	protected HttpServletResponse response;
	protected HttpSession session;
	@InitBinder
    public void initBinder(ServletRequestDataBinder binder) {
        /**
         * 自动转换日期类型的字段格式
         */
        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat(Constants.DATETIME_FORMAT), true));
        /**
         * 防止XSS攻击
         */
        binder.registerCustomEditor(String.class, new StringEscapeEditor(true, false));
    }
	
	@ModelAttribute
	public void setHttpServletPrama(HttpServletRequest request,HttpServletResponse response){
		this.request = request;
		this.response = response;
		this.session = this.request.getSession();
	}
	
	/** 获取当前用户Id */
	protected Long getCurrUser() {
		if(Constants.IS_TOKEN){
			Object userId = WebUtil.getCurrentUser(this.request);
			if(DataUtil.isEmpty(userId)){
				return -1L;
			}
			if(userId instanceof String){
				return Long.parseLong((String)userId);
			}else if(userId instanceof Long){
				return (Long)userId;
			}else{
				System.err.println("获取当前用户ID时，该数据的类型不合法："+userId.getClass().getName());
				return -1L;
			}
		}else{
			return -1L;
		}
	}
	
	protected void setCreateInfo(BaseEntity entity){
		entity.setCreateBy(getCurrUser());
		entity.setCreateTime(DateUtil.getNow());
	}
	
	/** 异常处理 */
	@ExceptionHandler(Exception.class)
	public void exceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception ex)
			throws Exception {
		logger.error(Constants.Exception_Head, ex);
		response.setContentType("application/json;charset=UTF-8");
		
		if(ex instanceof com.alibaba.dubbo.rpc.RpcException){
			String msg = StringUtils.defaultIfBlank(ex.getMessage(), "Dubbo服务调用出现异常，请联系管理员！");
			
			Result result = new Result();
			result.setMsg(msg.length() > 100 ? "微服务远程调用失败，请联系管理员！" : msg);
			result.setSuccess(false);
			result.setObj(System.currentTimeMillis());
			String reStr = JsonUtil.toJson(result);
			logger.info(reStr);
			byte[] bytes = reStr.getBytes("UTF-8");
			response.getOutputStream().write(bytes);
			return;
		}
		
		String msg = StringUtils.defaultIfBlank(ex.getMessage(), "系统走神了,请稍候再试!");
		Result result = new Result();
		result.setMsg(msg.length() > 100 ? "系统走神了,请稍候再试！" : msg);
		result.setSuccess(false);
		result.setObj(System.currentTimeMillis());
		String reStr = JsonUtil.toJson(result);
		logger.info(reStr);
		byte[] bytes = reStr.getBytes("UTF-8");
		response.getOutputStream().write(bytes);
		
	}
}
